package AIO;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;

/**
 * @author fei.fang
 * @date 2021/8/24
 **/
public class ClientChannelHandler implements CompletionHandler<Integer, Attachment> {
    @Override
    public void completed(Integer result, Attachment attachment) {
        ByteBuffer buffer = attachment.getBuffer();
        if (attachment.isReadMode()) {
            buffer.flip();
            byte[] bytes = new byte[buffer.limit()];
            buffer.get(bytes);
            String msg = new String(bytes);
            System.out.println("收到服务器：" + msg);

            attachment.setReadMode(false);
            buffer.clear();
            String newMsg = "new Msg from AioClient";
            buffer.put(newMsg.getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            attachment.getChannel().write(buffer, attachment, this);
        }else{
            attachment.setReadMode(true);
            buffer.clear();
            attachment.getChannel().read(buffer, attachment, this);
        }
    }

    @Override
    public void failed(Throwable exc, Attachment attachment) {
        System.out.println("连接断开");
    }
}
